import datetime
import jwt
import requests
from django.shortcuts import redirect
from rest_framework.response import Response
from rest_framework.views import APIView
from ThreeLogin.models import OpenUser
from django_blog.settings import WEIBO_App_Key, WEIBO_App_Secret, WEIBO_URL, SECRET_KEY


class WeiboLoginView(APIView):
    # 使用微博开放平台OAuth2/authorize接口 可以使用get和post
    def get(self, request):
        micro_url = 'https://api.weibo.com/oauth2/authorize?client_id={}&redirect_uri={}'.format(WEIBO_App_Key, WEIBO_URL)
        return Response({'url': micro_url})

    # 使用新浪开放平台OAuth2/access_token接口, 只能使用post方法
    def post(self, request):
        # 获取code, 去访问token
        code = request.data.get('code', None)
        # 使用requests网络请求请求
        r = requests.post('https://api.weibo.com/oauth2/access_token', {
            'client_id': WEIBO_App_Key,
            'client_secret': WEIBO_App_Secret,
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': WEIBO_URL
        })
        # 获取返回的对象
        print(r.json())
        access_token = r.json()['access_token']
        uid = r.json()['uid']
        return Response({'msg': '登录成功','code': 200, 'uid': uid.uid})